using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using VirtualDeveloper.CodeTransformation;
using VirtualDeveloper.Filters;

namespace VirtualDeveloper
{
    internal class Developer
    {
        private readonly IEnumerator<ILineTransformer> lineTransformersEnumerator;

        public Developer(IEnumerable<ILineTransformer> lineTransformers)
        {
            lineTransformersEnumerator = lineTransformers.GetEnumerator();
        }
        
        public Developer(params ILineTransformer[] lineTransformers)
        {
            lineTransformersEnumerator = new RoundRobinEnumerator<ILineTransformer>(lineTransformers);
        }

        public string Code()
        {
            using (var stream = GetType().Assembly.GetManifestResourceStream("VirtualDeveloper.ExistingCode.txt"))
                // ReSharper disable AssignNullToNotNullAttribute
            using (var reader = new StreamReader(stream))
                // ReSharper restore AssignNullToNotNullAttribute
            {
                return reader.ReadToEnd();
            }
        }

        public string Code(string inputCode, params string[] newCodes)
        {
            if (!newCodes.Any())
            {
                newCodes = new List<string> { string.Empty }.ToArray();
            }

            var lines = inputCode.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            var modifiedLines = new StringBuilder();
            var roundRobinToAdd = new RoundRobinEnumerator<string>(newCodes);

            foreach (var line in lines)
            {
                roundRobinToAdd.MoveNext();
                lineTransformersEnumerator.MoveNext();
                // ReSharper disable PossibleNullReferenceException
                modifiedLines.AppendLine(lineTransformersEnumerator.Current.ModifyLine(line, roundRobinToAdd.Current));
                // ReSharper restore PossibleNullReferenceException
            }

            return modifiedLines.ToString().TrimEnd();
        }
    }
}